package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    @Lazy
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public String sendCode(String phone, HttpSession session) {
        // 校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            throw new RuntimeException("手机号格式错误");
        }
        // 生成验证码
        String code = RandomUtil.randomNumbers(6);
        // 保存验证码到session
        //session.setAttribute("code", code);

        // 保存验证码到redis中
        stringRedisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY + phone, code, 2, TimeUnit.MINUTES);

        // 发送验证码（此处应该使用短信发送平台，但是为了方便，直接返回验证码）
        log.info("验证码发送成功：{}", code);
        return code;
    }

    @Override
    public String login(LoginFormDTO loginForm, HttpSession session) {
        // 校验手机号
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)) {
            throw new RuntimeException("手机号格式错误");
        }
        // 校验验证码
        String code = loginForm.getCode();
        // 从session中获取验证码
        //Object cacheCode = session.getAttribute("code");
        // 从redis中获取验证码
        String cacheCode = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + phone);
        if (!Objects.equals(code, cacheCode) || Objects.isNull(cacheCode)) {
            throw new RuntimeException("验证码错误");
        }
        // 根据手机号查询用户
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class).eq(User::getPhone, phone);
        User user = this.getOne(wrapper);
        if (Objects.isNull(user)) {
            // 如果用户不存在，创建新用户并保存
            user = this.createUserWithPhone(phone);
        }
        // 保存用户到session
        //session.setAttribute("user", BeanUtil.copyProperties(user, UserDTO.class));

        // 保存用户到redis中
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        // 随机生成token，作为登录令牌
        // 使用UUID生成token
        String token = UUID.randomUUID().toString(true);
        // 将user对象转为hash存储
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        // 忽略空的值
                        .ignoreNullValue()
                        // 修改字段值
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        // 将用户信息存入redis中
        stringRedisTemplate.opsForHash().putAll(RedisConstants.LOGIN_USER_KEY + token, userMap);
        // 设置有效期30分钟
        stringRedisTemplate.expire(RedisConstants.LOGIN_USER_KEY + token, RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        // 返回token
        return token;
    }

    private User createUserWithPhone(String phone) {
        User user = new User();
        String nickName = SystemConstants.USER_NICK_NAME_PREFIX + RandomUtil.randomString(10);
        user.setPhone(phone);
        user.setNickName(nickName);
        user.setCreateTime(LocalDateTime.now());
        this.save(user);
        return user;
    }
}
